package com.example.service.impl;

import com.example.mapper.EmpExprMapper;
import com.example.mapper.EmpLogMapper;
import com.example.mapper.EmpMapper;
import com.example.pojo.*;
import com.example.service.EmpLogService;
import com.example.service.EmpService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService  {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;  //同层注入
    @Override
    public PageResult<Emp> findEmpAndDept(Integer page, Integer pageSize) {
        PageResult<Emp> pageResult = new PageResult<>();
        pageResult.setRows(empMapper.selectEmpAndDept((page-1)*pageSize, pageSize));
        pageResult.setTotal(empMapper.count());
        return pageResult;
    }


    @Override
    public PageResult<Emp> searchEmp(EmpQueryParam empQueryParam) {
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        //执行分页查询，获得查询结果，执行两次，有一次是为了获得总记录数
        //PageHelper获得分页查询结果集，并将结果集封装成Page对象，Page对象实现了List接口
        List<Emp> emps = empMapper.searchEmp(empQueryParam);
        //将结果封装成PageResult对象
        Page<Emp> pageInfo = (Page<Emp>) emps;
        return new PageResult<Emp>(pageInfo.getTotal(), pageInfo.getResult());
    }

    @Transactional  // 事务注解，用于事务控制
    @Override
    public void addEmp(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insertEmp(emp);  // 插入员工信息表,并获得自增的id

            for (EmpExpr expr :emp.getExprList()) {
                expr.setEmpId(emp.getId());
    //            empMapper.insertEmpExpr(expr);// 遍历一次插入一次，效率低
            }
            empExprMapper.insertEmpExpr(emp.getExprList());  // 插入员工工作经历信息表
        } finally {
            EmpLog empLog = new EmpLog(null,LocalDateTime.now(),"新增员工："+emp);//这里emp自动使用toString方法
            empLogService.insertLog(empLog);  // 记录日志
        }

    }

    @Transactional
    @Override
    public void deleteEmp(List<Integer> IDs) {
        try {
            empMapper.deleteEmp(IDs);
            empExprMapper.deleteEmpExpr(IDs);
        } finally {
            EmpLog emplog =new EmpLog(null,LocalDateTime.now(),"删除员工: "+ IDs);
            empLogService.insertLog(emplog);
        }
    }

    @Override
    public Emp getEmpById(Integer id) {
        return empMapper.searchEmpById(id);
    }
}
